package homework.chatone;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class ChatServer {
    private ServerSocket serverSocket;
    private Map<String,PrintWriter  > map = new HashMap<>();
    private String name;
    private String host;
    public ChatServer() {
        try {
            System.out.println("服务器启动...");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务器启动成功...");
        } catch (IOException e) {
            System.out.println("服务器启动失败");
            e.printStackTrace();
            System.exit(1);
        }
    }

    class ClientHandle implements Runnable {
        private Socket socket;

        public ClientHandle(Socket socket) {
            this.socket = socket;
            host = this.socket.getInetAddress().getHostAddress();
        }

        @Override
        public void run() {
            try {
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));

                    PrintWriter pw = new PrintWriter(
                            new BufferedWriter(
                                    new OutputStreamWriter(socket.getOutputStream(),StandardCharsets.UTF_8)
                            ),true);

                    name = br.readLine();
                    synchronized (map) {
                        map.put(name, pw);
                    }
                    sendMessageToAllClient(name+"上线啦");

                    String data;
                    while ((data = br.readLine()) != null) {

                        if (data.startsWith("@")){
                            sendMessageToOneClient(data);
                        }else {
                            sendMessageToAllClient(data);
                        }

                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {

                try {
                    synchronized (map){
                    map.remove(name);
                }
                    socket.close();
                    System.out.println("客户端"+host+"退出聊天");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                if (map.isEmpty()){
                    return;
                }
            }
        }
    }
     private void sendMessageToAllClient (String data){
         System.out.println(host + "说:" + data);

         synchronized (map){
             Collection<PrintWriter> values = map.values() ;
             for (PrintWriter out:values){
                 out.println(host + "说:" + data);
             }
         }

    }

    private void sendMessageToOneClient (String data) {
        String msg = data.substring(data.lastIndexOf(":"));

        String name =data.substring(1,data.lastIndexOf(":"));

        if (map.containsKey(name)){
            map.get(name).println(host+"说"+msg);
        }else {
            sendMessageToAllClient(name+"用户下线了");
        }

        }



    public void start() {
        try {
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("客户端：" + socket + "连接成功");
                new Thread(new ClientHandle(socket)).start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public static void main(String[] args) {
        new ChatServer().start();

    }
}
